﻿using Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class Message
{
	private byte[] data = new byte[1024];
	private int startIndex = 0;

	public int RemainSize {

		get { return Data.Length - StartIndex; }
	}

	public byte[] Data {
		get {
			return data;
		}

		set {
			data = value;
		}
	}

	public int StartIndex {
		get {
			return startIndex;
		}

		set {
			startIndex = value;
		}
	}

	public void AddCount(int count) {

		StartIndex += count;
	}
	public void GetMessage(Action<ActionCode, string> processData) {
		while (true) {
			if (StartIndex <= 4) {
				return;
			}
			int count = BitConverter.ToInt32(Data, 0);
			if (StartIndex - 4 >= count) {
				ActionCode acCount = (ActionCode)BitConverter.ToInt32(Data, 4);
				string mes = Encoding.UTF8.GetString(Data, 8, count - 4);
				Debug.Log(mes);
				processData(acCount, mes);
				Array.Copy(Data, count + 4, Data, 0, StartIndex - 4 - count);
				StartIndex -= (count + 4);
			} else {
				break;
			}
		}
	}
	public byte[] SendData(RequestCode requestCode, ActionCode actionCode, string data) {
		byte[] data0 = BitConverter.GetBytes((int)requestCode);
		byte[] data1 = BitConverter.GetBytes((int)actionCode);
		byte[] data2 = Encoding.UTF8.GetBytes(data);
		int length = data0.Length + data1.Length + data2.Length;
		byte[] data3 = BitConverter.GetBytes(length);
		byte[] newData = data3.Concat(data0).Concat(data1).Concat(data2).ToArray();
		return newData;
	}
}
